package com.example.newinfinity.View.DrawShape

import android.graphics.Canvas
import android.graphics.Paint

//画箭头
class LocationShape() : Shape() {
    // 箭头长度和宽度
    private val arrowLength = 50f // 箭头长度
    private val arrowWidth = 8f  // 箭头宽度

    override fun draw(canvas: Canvas) {
        // 计算中心点
        val midX = (startX + endX) / 2f
        val midY = (startY + endY) / 2f

        // 绘制水平主线段（X轴）
        canvas.drawLine(startX, midY, endX, midY, mPaint)
        // 绘制垂直主线段（Y轴）
        canvas.drawLine(midX, startY, midX, endY, mPaint)

        // 绘制箭头（X轴右端）
        drawArrow(canvas, endX - arrowLength, midY, endX, midY, mPaint)
        // 绘制箭头（Y轴上端）
        drawArrow(canvas, midX, startY + arrowLength, midX, startY, mPaint)

        //继承父类 拖拉点拽状态为selected时显示边框及四个拖拉圆点
        super.draw(canvas)
    }

    private fun drawArrow(
        canvas: Canvas,
        fromX: Float,
        fromY: Float,
        toX: Float,
        toY: Float,
        paint: Paint
    ) {
        // 计算箭头方向的角度
        val angle = Math.atan2((toY - fromY).toDouble(), (toX - fromX).toDouble())
        val sin = Math.sin(angle)
        val cos = Math.cos(angle)

        // 计算箭头两侧点坐标
        val leftX = (toX - arrowLength * cos + arrowWidth * sin).toFloat()
        val leftY = (toY - arrowLength * sin - arrowWidth * cos).toFloat()
        val rightX = (toX - arrowLength * cos - arrowWidth * sin).toFloat()
        val rightY = (toY - arrowLength * sin + arrowWidth * cos).toFloat()

        // 绘制箭头两条边
        canvas.drawLine(toX, toY, leftX, leftY, paint)
        canvas.drawLine(toX, toY, rightX, rightY, paint)
    }

    override fun fillColor() {
        super.fillColor()
    }

    override fun containsPointInPath(x: Float, y: Float): Boolean {
        val middleX = (startX + endX) / 2
        val middleY = (startY + endY) / 2
        //计算触摸点是否点在x轴上
        val a = (startX - x) * (startX - x) + (middleY - y) * (middleY - y)
        val reallyA = Math.sqrt(a.toDouble())
        val b = (endX - x) * (endX - x) + (middleY - y) * (middleY - y)
        val reallyB = Math.sqrt(b.toDouble())
        val lineLengthX = endX - startX
        //计算触摸点是否点在y轴上
        val c = (middleX - x) * (middleX - x) + (startY - y) * (startY - y)
        val reallyC = Math.sqrt(c.toDouble())
        val d = (middleX - x) * (middleX - x) + (endY - y) * (endY - y)
        val reallyD = Math.sqrt(d.toDouble())
        val lineLengthY = endY - startY
        return reallyA + reallyB < lineLengthX + 1 || reallyC + reallyD < lineLengthY + 1
    }

}